<template>
  <div>
    <!--引用表格-->
   <BasicTable @register="registerTable" :rowSelection="rowSelection">
     <!--插槽:table标题-->
      <template #tableTitle>
          <a-button type="primary" v-auth="'wmhb:wm_contract:add'" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
          <a-button  type="primary" v-auth="'wmhb:wm_contract:exportXls'" preIcon="ant-design:export-outlined" @click="onExportXls" v-if="false"> 导出</a-button>
          <j-upload-button type="primary" v-auth="'wmhb:wm_contract:importExcel'" preIcon="ant-design:import-outlined" @click="onImportXls" v-if="false">导入</j-upload-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandleDelete" v-if="hasPermission('wmhb:wm_contract:deleteBatch')">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                  <a-menu-item key="2" @click="batchHandleConfirm" v-if="hasPermission('wmhb:wm_contract:confirm')">
                    <Icon icon="ant-design:check-circle-outlined"></Icon>
                    确认
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button>批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
        <template v-if="column.dataIndex==='file'">
          <!--文件字段回显插槽-->
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
        </template>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <WmContractModal @register="registerModal" @success="handleSuccess"></WmContractModal>
    <ContractBomImptModal @register="bomImptModal" @success="handleSuccess"></ContractBomImptModal>
    <ContractBomChangeModal @register="bomChangeModal" @success="handleSuccess"></ContractBomChangeModal>
    <ContractProdMapModal @register="bomMapModal" @success="handleSuccess"></ContractProdMapModal>
    <ContractBomListModal @register="bomListModal" @success="handleSuccess"></ContractBomListModal>
  </div>
</template>

<script lang="ts" name="wmhb-wmContract" setup>
  import {ref, reactive, computed, unref} from 'vue';
  import {usePermission} from "@/hooks/web/usePermission";
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import {useModal} from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import WmContractModal from './components/WmContractModal.vue'
  import ContractBomImptModal from "./components/ContractBomImptModal.vue";
  import ContractBomChangeModal from "./components/ContractBomChangeModal.vue";
  import ContractProdMapModal from "@/views/wmhb/contract/components/ContractProdMapModal.vue";
  import ContractBomListModal from "@/views/wmhb/contract/components/ContractBomListModal.vue";
  import {columns, searchFormSchema, superQuerySchema} from './WmContract.data';
  import {list, deleteOne, batchDelete,confirmContract, getImportUrl,getExportUrl,confirmBatchBom} from './WmContract.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';

  const userStore = useUserStore()
  const {hasPermission} = usePermission()
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  //注册model
  const [registerModal, {openModal}] = useModal();
  const [bomImptModal,{openModal:openBomImptModal}] = useModal()
  const [bomChangeModal,{openModal:openBomChangeModal}] = useModal()
  const [bomMapModal,{openModal:openBomMapModal}] = useModal()
  const [bomListModal,{openModal:openBomListModal}] = useModal()
  //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '合同管理',
           api: list,
           columns,
           canResize:false,
           showIndexColumn:true,
           size:'small',
           formConfig: {
              //labelWidth: 120,
              schemas: searchFormSchema,
              autoSubmitOnEnter:true,
              showAdvancedButton:true,
              autoAdvancedCol: 2,
              baseColProps: { span: 8 },
            },
           actionColumn: {
               width: 180,
               fixed:'right'
            },
            beforeFetch: (params) => {
              return Object.assign(params, queryParam);
            },
      },
       exportConfig: {
            name:"合同管理",
            url: getExportUrl,
            params: queryParam,
          },
          importConfig: {
            url: getImportUrl,
            success: handleSuccess
          },
  })

  const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
   /**
    * 新增事件
    */
  function handleAdd() {
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }

  async function handleConfirm(record){
    const params = {ids:[record.id]}
    await confirmContract(params,handleSuccess)
  }

  async function batchHandleConfirm(){
    await confirmContract({ids:selectedRowKeys.value},handleSuccess)
  }

   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         {
          label: '确认',
          tooltip:'合同确认',
          ifShow:['PREPARE'].includes(record.status),
          onClick: handleConfirm.bind(null,record),
          auth:'wmhb:wm_contract:confirm',
         },
         {
           label: '导入',
           tooltip: '导入合同产品清单',
           ifShow: ['CONFIRMED'].includes(record.status),
           onClick:handleBomFunc.bind(null,record,2),
           auth:'wmhb:wm_contract_product:importExcel'
         },
         {
           label: '导入确认',
           tooltip: '导入合同产品清单',
           ifShow: ['IMPORTED'].includes(record.status),
           onClick:confirmImported.bind(null,record),
           auth:'wmhb:wm_contract_product:confirm'
         },
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
           auth:'wmhb:wm_contract:edit'
         }
       ]
   }

   function handleBomFunc(record,actNum){
     switch (actNum) {
       case 1:
         openBomListModal(true,{
           record
         })
         break
       case 2:
         openBomImptModal(true,{
           record
         })
         break
       case 3:
         openBomChangeModal(true,{
           record,
           isUpdate:true
         })
         break
       case 4:
         openBomMapModal(true,{
           record
         })
         break
       default:
         break
     }
   }

   function confirmImported(record){
    confirmBatchBom({batchNo:record.batchNo},handleSuccess)
   }

     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
      let baseAction=[
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         },
         {
           label: '删除',
           popConfirm: {
             title: '是否确认删除',
             confirm: handleDelete.bind(null, record),
             placement: 'topLeft',
           },
           auth:'wmhb:wm_contract:delete'
         },
        {
           label: '变更合同产品清单',
           tooltip:'已导入合同产品清单',
           ifShow: ['IMPORTED','IMPORT_CONFIRMED'].includes(record.status),
           onClick:handleBomFunc.bind(null,record,3),
           auth:'wmhb:wm_contract_product:edit'
         }
      ]
      let actBtns = <any>[]
      switch (record.status) {
        case 'IMPORT_CONFIRMED':
          actBtns = [
            {
               label: '产品与计划映射表',
               onClick:handleBomFunc.bind(null,record,4),
               auth:'wmhb:wm_contract_product:product_task_map'
             },
            {
               label: 'BOM清单报表',
               onClick:handleBomFunc.bind(null,record,1),
               auth:'wmhb:wm_contract_product:bom_list_report'
             }
          ]
          break
        default:
          break
      }
      baseAction.push(...actBtns)
      return baseAction
   }


</script>

<style lang="less" scoped>
  :deep(.ant-picker),:deep(.ant-input-number){
    width: 100%;
  }
</style>
